/**
 * Created by 白雨浓 on 2018/1/24 9:32.
 */
import electron from 'electron';
import path from 'path';
import fs from 'fs';
import ejs from 'ejs';

export default {
    insert(self, name, fields){
        const dataPath = (electron.app || electron.remote.app).getPath('userData');
        const filePath = path.join(dataPath, 'insert.ejs');
        if (!fs.existsSync(filePath)) {
            self.$$msg.error('insert模板文件缺失');
            return;
        }
        const tmpFile = fs.readFileSync(filePath, 'utf-8');

        const sNames = [];
        const jNames = [];

        const debars = ['id', 'state'];

        for (let i = 0; i < fields.length; i++) {
            const field = fields[i];
            if (debars.indexOf(field.COLUMN_NAME) < 0) {
                let name = '`' + field.COLUMN_NAME + '`';
                if (i !== fields.length - 1)
                    name += ',';
                sNames.push(name);
            }
        }

        for (let i = 0; i < fields.length; i++) {
            const field = fields[i];
            if (debars.indexOf(field.COLUMN_NAME) < 0) {
                let name = '';
                if (field.COLUMN_NAME === 'create_time' || field.COLUMN_NAME === 'update_time')
                    name = 'NOW()';
                else {
                    const tn = self.$str.toCamel(field.COLUMN_NAME);
                    name = `#{${tn}}`;
                }

                if (i !== fields.length - 1)
                    name += ',';
                jNames.push(name);
            }
        }

        const tmp = {
            dbName: self.config.dbName,
            tableName: name,
            sNames: sNames,
            jNames: jNames
        };

        return ejs.render(tmpFile, tmp);
    }
}